// 这里是axios的所有的配置
import axios from "axios";
//引入参数转化模块
import qsString from "querystring";
//引入封装好的 路由模块
import router from "../router";

let baseUrl = "/api";

//设置拦截器
//请求拦截器
axios.interceptors.request.use((req) => {

  //设置请求头 设置token
  //  
  // console.log(req, "req");
  if (req.url != "/api/userlogin") {
    //添加token
    req.headers.authorization = sessionStorage.getItem("userinfo")
      ? JSON.parse(sessionStorage.getItem("userinfo")).token
      : null;
  }
  //一定要记得返回
  return req;
});
//响应拦截器
axios.interceptors.response.use((res) => {
  
  //一般工作是通过code码去判断逻辑
  if (res.data.msg == "请设置请求头,并携带验证字符串") {
    alert(res.data.msg);
    //强制跳转到登录
    router.push("/login");
  } else if (res.data.msg == "登录已过期或访问权限受限") {
    alert(res.data.msg);
    //强制跳转到登录
    router.push("/login");
  } else {
    //一定要记得返回
    return res.data;
  }
});


export const get = (url, params = {}) => {
  return new Promise((resolve, reject) => {
    //调用axios的get
    axios
      .get(baseUrl + url, {
        params,
      })
      .then((res) => resolve(res))
      .catch((err) => reject(err));
  });
};

/* 
post 

*/
export const post = (url, params = {}, isFile = false) => {
  //设置一个空对象
  let data = {};
  if (isFile) {
    //有上传文件 要修改content-type
    data = new FormData();
    for (let i in params) {
      data.append(i, params[i]);
    }
  } else {
    data = qsString.stringify(params);
  }
  return new Promise((resolve, reject) => {
    //调用axios的get
    axios
      .post(baseUrl + url, data)
      .then((res) => resolve(res))
      .catch((err) => reject(err));
  });
};
